package com.example.demo.controller.v1;

import com.example.demo.dao.BookDao;
import com.example.demo.entity.Book;
import com.example.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/book")
public class BookApiController {
    @Autowired
    private BookService bookService;

    @Autowired
    private BookDao bookDao;

    @GetMapping("")
    public Object list() {
        List<Book> list = bookService.listAll();
        if (list == null) return "{\"msg\":\"无数据\"}";
        return bookService.listAll();
    }

    @PostMapping("/store")
    public String store(Book book) {
        int save = bookService.save(book);
        if (save > 0) return "{\"msg\":\"新增成功\"}";
        return "{\"msg\":\"新增失败\"}";
    }
    @GetMapping("show")
    public Object show(@RequestParam int bookId) {
        Optional<Book> book = bookDao.findById(bookId);
        if (book.isEmpty()) return "{\"msg\":\"无数据\"}";
        return book.get();
    }

    @PostMapping("/update")
    public String update(Book book) {
        int save = bookService.save(book);
        if (save > 0) return "{\"msg\":\"更新成功\"}";
        return "{\"msg\":\"更新失败\"}";
    }

    @DeleteMapping("/delete")
    public String delete(@RequestParam int bookId) {
        int delete = bookService.delete(bookId);
        if (delete > 0) return "{\"msg\":\"删除成功\"}";
        return "{\"msg\":\"删除失败\"}";
    }
}
